package com.zretc.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zretc.entity.Seller;

/**
 * @author wentao
 * 商家登录session判断（没有登录则提示登录并返回登录界面）
 * Servlet Filter implementation class SellerLoginSessionFilter
 */
@WebFilter("/sellerSissionFilter")
public class SellerLoginSessionFilter implements Filter {

    /**
     * Default constructor. 
     */
    public SellerLoginSessionFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		// 转换为http类
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		
		// 获取session
		HttpSession session = request.getSession();
		
		// 获取session中的seller
		Seller seller = (Seller)session.getAttribute("seller");
		// 判断路径
		String pathURI = request.getRequestURI();
		
		// 判断是否是商家的url
		if(pathURI.startsWith(request.getContextPath()+"/back/seller")) {
			if(pathURI.endsWith("sellerSignIn.jsp") ||pathURI.endsWith("sellerSignUp.jsp") || pathURI.endsWith("SellerServlet")||pathURI.endsWith(".css")||pathURI.endsWith(".js")||pathURI.endsWith(".woff")||pathURI.endsWith(".tff")) {
				chain.doFilter(req, res);
			}else {
				// 判断是否存在
				if(seller == null || seller.getSellerStatus()==0) {
					response.setContentType("text/html");
					// alert弹框提示没有权限，请登录
					PrintWriter out = response.getWriter();
					
					out.write("<script>alert('没有权限，请登录！！!');");
					// 重定向到登录界面
					out.write("location.href='"+request.getContextPath()+"/back/sellerSignIn.jsp';");
					out.write("</script>");
					out.flush();
					out.close();
					
					
				}else {
					chain.doFilter(req, res);
				}
			}
		}else {
			chain.doFilter(req, res);
		}
		
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
